<template>
  <BasicModal footer-hide v-bind="$attrs" @register="register" width="60%" :centered="centered" @ok="handleAfterClose">
    <a-spin :spinning="loading" size="large" tip="Loading...">
      <a-tree style="padding:10px 20px;"
        checkable
        :tree-data="treeData"
        :show-checkbox="false"
        v-model:expandedKeys="expandedKeys"
        v-model:checkedKeys="checkedKeys"
        :selectable="false"
      >
      </a-tree>
    </a-spin>
  </BasicModal>
</template>

<script setup lang="ts">
  import { onMounted, reactive, ref, watch } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { commonFunctionsList, saveCommonFunctionsList } from '../../api.ts';
  const emits = defineEmits(['updateCommonFunctions']);
  let treeData = reactive([]);
  let checkedKeys = ref([]);
  let expandedKeys = ref([]);
  let loading = ref(false);
  const [register, { closeModal }] = useModalInner((data) => {
    let newArr = [];
    if(data.commonFunctionsList.length>0){
      data.commonFunctionsList.forEach(item => {
        newArr.push(item.id);
      })
    }
    checkedKeys.value = newArr;
    expandedKeys.value = newArr;
  });
  // 获取常用功能原始列表
  const  getCommonFunctionsList = async () =>{
    loading.value = true;
    const result = await  commonFunctionsList();
    treeData = convertToTreeData(result.result);
    loading.value = false;
  }
  const convertToTreeData = (data) => {
    const uniqueMap = {};
    let result = [];
    // 去出数组中为null，id重复的数据
    data.forEach(item => {
      if (item !== null && !uniqueMap[item.id] && (!item.hidden || !item.hideTab) && item.component!==null) {
        uniqueMap[item.id] = item;
      }
    });
    const sortedData = Object.values(uniqueMap).sort((a, b) => (a.sortNo || 0) - (b.sortNo || 0));
    // 使用parentId作为键创建项的映射
    const itemMap = {};
    sortedData.forEach(item => {
      if (item.parentId) {
        if (!itemMap[item.parentId]) {
          itemMap[item.parentId] = [];
        }
        if (!item.hidden || !item.hideTab) {
          itemMap[item.parentId].push(item);
        }
      } else {
        result.push(item);
      }
    });

    // 创建树形结构的数据
    const buildTree = (items) => {
      return items.map(item => {
        if (itemMap[item.id]) {
          return {
            title: item.name,
            key: item.id,
            disabled: true,
            children: buildTree(itemMap[item.id])
          };
        } else {
          return {
            title: item.name,
            key: item.id,
            disabled: false
          };
        }
      });
    };
    result = buildTree(result);
    return result;
  }
  const centered = ref(true);
  const handleAfterClose = async () => {
    let newString = checkedKeys.value.join(';');
    let params = {
      'commonModules':newString,
    }
    let result = await saveCommonFunctionsList(params);
    if(result.result === '添加成功'){
      emits('updateCommonFunctions');
      closeModal();
    }
  };
  watch(checkedKeys, () => {
    if(checkedKeys.value.length===7){
      changeTree(treeData,checkedKeys.value);
    }else{
      resetTree(treeData);
    }
  });
  watch(expandedKeys, () => {
  });
  // 树形结构元素给每个元素的disabled设置为true;
  const changeTree = (items,checkTree) => {
    items.forEach(item =>{
      if (item.children && item.children.length) {
         changeTree(item.children,checkTree)
      } else {
        if (checkTree.includes(item.key)) {
         item.disabled = false;
        } else {
         item.disabled = true;
        }
      }
    })
    return items;   
  };
  // 恢复原始数据结构
  const resetTree = (items) => {
    items.forEach(item => {
      if (item.children && item.children.length) {
        resetTree(item.children);
      }else{
        item.disabled = false;
      }
    });
  };
  onMounted(()=>{
    getCommonFunctionsList();
  })
  defineExpose({
    getCommonFunctionsList,
  })
</script>
<style lang="less" scoped>
  :deep(.ant-tree-list){
    padding: 0 20px;
  }
</style>
<style>
.ant-spin-nested-loading > div > .ant-spin{
  min-height: 200px;
}
</style>
